package com.pkche.core.advanced.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.activation.MimetypesFileTypeMap;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;



/**
 * 封装了四种发送http请求的方法
 * get、post、put、delete
 * @author zhongpengzhan
 *
 */
@SuppressWarnings("JavadocReference")
public class HttpClientUtil {
	private final static Log log = LogFactory.getLog(HttpClientUtil.class);
	
	private static final String GZIP_CONTENT_TYPE = "application/x-gzip";
	private static final String USER_AGENT = "";
	
	private HttpClientUtil() {}
	
	
	
	/**
	 * 发送HTTP_GET请求
	 * @see 该方法会自动关闭连接,释放资源
	 * @param reqURL 请求的url地址(含参数),默认采用utf-8编码
	 * @return
	 */
	public static String sendGetRequest(String reqURL){
		return sendGetRequest(reqURL,null,false);
	}
	
	/**
     * 发送HTTP_POST请求  时默认采用UTF-8解码
     * @see 该方法会自动关闭连接,释放资源
     * 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
     * @param reqURL  请求的url
     * @param params 请求参数 
     * @return
     */
	public static String sendPostRequest(String reqURL, Map<String, String> params){
		return sendPostRequest(reqURL, params, null, null);
	}
	
	/**
     * 发送HTTP_POST请求  时默认采用UTF-8解码
     * @see 该方法会自动关闭连接,释放资源
     * 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
     * @param reqURL  请求的url
     * @param sendData 请求参数
     * @param isEncoder 请求编码
     * @return
     */
	public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder){
		return sendPostRequest(reqURL, sendData, isEncoder, null, null);
	}
	
	/**
     * 发送HTTP_POST请求  时默认采用UTF-8解码
     * @see 该方法会自动关闭连接,释放资源
     * 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
     * @param reqURL  请求的url
     * @param sendData 请求参数 
     * @param isEncoder 请求编码
     * @param isGzip 是否压缩
     * @return
     */
	public static String sendPostRequest(String reqURL, String sendData, boolean isGzip, boolean isEncoder){
		return sendPostRequest(reqURL, sendData, isGzip, isEncoder, null, null);
	}
	
	/**
     * 发送HTTPS_POST请求
     * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
     * @see 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
     */
	public static String sendPostSSLRequest(String reqURL, Map<String, String> params){
        return sendPostSSLRequest(reqURL, params, null, null);
    }
	
	/**
     * 发送HTTP_PUT请求  时默认采用UTF-8解码
     * @see 该方法会自动关闭连接,释放资源
     * 该方法会自动对<code>params</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
     * @param reqURL  请求的url
     * @param params 请求参数 
     * @return
     */
	public static String sendPutRequest(String reqURL, Map<String, String> params){
		return sendPutRequest(reqURL, params, null, null);
	}
	
	/**
     * 发送HTTP_PUT请求
     * @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
     * @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][ ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
     * @param isEncoder 用于指明请求数据是否需要UTF-8编码,true为需要
     * @param isGzip 是否压缩
     * @param reqURL 请求的url
     * @param params 请求参数 
     */
	public static String sendPutRequest(String reqURL, String sendData, boolean isGzip, boolean isEncoder){
        return sendPutRequest(reqURL, sendData, isGzip, isEncoder, null, null);
    }
	
	/**
	 * 发送HTTP_DELETE请求
	 * @see 该方法会自动关闭连接,释放资源
	 * @param reqURL 请求的url地址(含参数),默认采用utf-8编码
	 * @return
	 */
	public static String sendDeleteRequest(String reqURL){
		return sendDeleteRequest(reqURL, null);
	}
	
	public static String sendGetRequest(String reqURL, String encoding, Boolean inGZIP){
		long responseLength = 0;//响应长度
		String responseContent = null; //响应内容
		HttpClient httpClient = new DefaultHttpClient(); 
		   
		HttpGet httpGet = new HttpGet(reqURL);  
		  
		if(inGZIP){
			httpGet.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);   
		}
		httpGet.setHeader(HTTP.USER_AGENT, USER_AGENT);
		   
		try {
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if(null != entity){
				responseLength = entity.getContentLength();
				String contentType = "";
				Header[] headers = httpGet.getHeaders(HTTP.CONTENT_TYPE);
				if(null != headers && headers.length > 0){
					contentType = headers[0].getValue();
				}
				 
				if(inGZIP) {
					responseContent = unGZipContent(entity, encoding == null ? Constants.DEFUALT_ENCODING : encoding);
				} else {
					responseContent = EntityUtils.toString(entity, encoding == null ? Constants.DEFUALT_ENCODING : encoding);
				}
				 
				close(entity); 
			}
			 
			log.debug("请求地址: " + httpGet.getURI());
			log.debug("响应状态: " + response.getStatusLine());
			log.debug("响应长度: " + responseLength);
			log.debug("响应内容: " + responseContent);

		   
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);

		} finally{
			httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
		}     
		return responseContent;
	}
	
	public static String sendGetSSLRequest(String reqURL){
        String responseContent = "";
		HttpClient httpClient = new DefaultHttpClient();
        X509TrustManager xtm = new X509TrustManager(){
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {return null;}
        };
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
            HttpGet httpGet = new HttpGet(reqURL);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
				responseContent = EntityUtils.toString(entity, Constants.DEFUALT_ENCODING );
          	  	close(entity); 
            }
            log.debug("请求地址: " + httpGet.getURI());
			log.debug("响应状态: " + response.getStatusLine());
			log.debug("响应内容: " + responseContent);
	              
        } catch (Exception e) {
            log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }
	
	
	public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
  	  	String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();	    	           
        HttpPost httpPost = new HttpPost(reqURL);
        httpPost.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
        httpPost.setHeader(HTTP.USER_AGENT, USER_AGENT);
        
        List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
        Set<Entry<String, String>>  paramSet = params.entrySet();
        
        if(null != paramSet && paramSet.size() > 0){
      	  	for(Entry<String,String> entry : paramSet){
      	  		formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      	  	}
        }	    	         
        try{
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? Constants.DEFUALT_ENCODING : encodeCharset));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
          	  	String contentType = "";
				Header[] headers = httpPost.getHeaders(HTTP.CONTENT_TYPE);
				if(headers != null && headers.length>0){
					contentType = headers[0].getValue();
				}
				 
				if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
					responseContent = unGZipContent(entity,decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
				}else{
					responseContent = EntityUtils.toString(entity, decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
				}
          	  	close(entity); 
            }
            
            log.debug("请求地址: " + httpPost.getURI());
			log.debug("响应状态: " + response.getStatusLine());
			log.debug("响应内容: " + responseContent);
        } catch(Exception e) {
            log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }
	
	public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset, String decodeCharset){
  	  	log.debug("参数："+sendData);
  	  	String responseContent = null;
  	  	HttpClient httpClient = new DefaultHttpClient();
  	  	HttpPost httpPost = new HttpPost(reqURL);
        
  	  	httpPost.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
  	  	httpPost.setHeader(HTTP.USER_AGENT, USER_AGENT);
        
  	  	try{
  	  		if(isEncoder){
  	  			List<NameValuePair> formParams = new ArrayList<NameValuePair>();
  	  			for(String str : sendData.split("&")){
  	  				formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
  	  			}
  	  			httpPost.setEntity(new StringEntity(URLEncodedUtils.format(formParams, encodeCharset==null ? Constants.DEFUALT_ENCODING  : encodeCharset)));
  	  		}else{
  	  			httpPost.setEntity(new StringEntity(sendData));	            	  
  	  		}
             
  	  		HttpResponse response = httpClient.execute(httpPost);
  	  		HttpEntity entity = response.getEntity();
            
  	  		if (null != entity) {
  	  			String contentType = "";
  	  			Header[] headers = httpPost.getHeaders(HTTP.CONTENT_TYPE);
  	  			if(null != headers && headers.length > 0){
  	  				contentType = headers[0].getValue();
  	  			}
				 
  	  			if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
  	  				responseContent = unGZipContent(entity,decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
  	  			}else{
  	  				responseContent = EntityUtils.toString(entity, decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
  	  			}
  	  			close(entity); 
  	  		}
            
  	  		log.debug("请求地址: " + httpPost.getURI());
  	  		log.debug("响应状态: " + response.getStatusLine());
  	  		log.debug("响应内容: " + responseContent);
            
        } catch(Exception e) {
        	log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }
	
	public static String sendPostRequest(String reqURL, String sendData,boolean isGzip, boolean isEncoder, String encodeCharset, String decodeCharset){
  	  	log.debug("参数："+sendData);
  	  	String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(reqURL);
        
        httpPost.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
        httpPost.setHeader(HTTP.USER_AGENT, USER_AGENT);
        
        try{
            if(isEncoder){
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                for(String str : sendData.split("&")){
                    formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
                }
                String paramStr = URLEncodedUtils.format(formParams, encodeCharset==null ? Constants.DEFUALT_ENCODING  : encodeCharset);
                if(isGzip) {
                	ByteArrayOutputStream baos = gZipContent(paramStr); 
		              
		            httpPost.setEntity(new ByteArrayEntity(baos.toByteArray()));
          	  	}else{
          	  		httpPost.setEntity(new StringEntity(paramStr));
          	  	}
            
            }else{
          	  	if(isGzip){
          	  		ByteArrayOutputStream baos = gZipContent(sendData); 
		              
		            httpPost.setEntity(new ByteArrayEntity(baos.toByteArray()));
          	  	}else{
          	  		httpPost.setEntity(new StringEntity(sendData));
          	  	}
            }	               
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            
            if (null != entity) {
          	  	String contentType="";
				Header[] headers=httpPost.getHeaders(HTTP.CONTENT_TYPE);
				if(headers!=null && headers.length>0){
					contentType=headers[0].getValue();
				}
				 
				if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
					responseContent = unGZipContent(entity,decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
				}else{
					responseContent = EntityUtils.toString(entity, decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
				}
          	  	close(entity); 
            }
            
            log.debug("请求地址: " + httpPost.getURI());
			log.debug("响应状态: " + response.getStatusLine());
			log.debug("响应内容: " + responseContent);
        }catch(Exception e){
            log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }
	
	public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
        String responseContent = "";
		HttpClient httpClient = new DefaultHttpClient();
        X509TrustManager xtm = new X509TrustManager(){
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {return null;}
        };
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{xtm}, null);
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
            HttpPost httpPost = new HttpPost(reqURL);
            
            httpPost.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
	          httpPost.setHeader(HTTP.USER_AGENT, USER_AGENT);
            
            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            for(Entry<String,String> entry : params.entrySet()){
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? Constants.DEFUALT_ENCODING : encodeCharset));
             
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
            	String contentType="";
				Header[] headers=httpPost.getHeaders(HTTP.CONTENT_TYPE);
				if(null != headers && headers.length > 0){
					contentType = headers[0].getValue();
				}
				 
				if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
					responseContent = unGZipContent(entity,decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
				}else{
					responseContent = EntityUtils.toString(entity, decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
				}
          	  	close(entity); 
           }
            
           log.debug("请求地址: " + httpPost.getURI());
           log.debug("响应状态: " + response.getStatusLine());
           log.debug("响应内容: " + responseContent);
        } catch (Exception e) {
            log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息为", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;
    }
	
	public static String sendPostSSLRequest(String requestUrl, String outputStr) {  
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化  
     	   X509TrustManager xtm = new X509TrustManager(){
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
                public X509Certificate[] getAcceptedIssuers() {return null;}
            };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null,  new TrustManager[]{xtm}, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            javax.net.ssl.SSLSocketFactory ssf = sslContext.getSocketFactory();  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式（GET/POST）  
            httpUrlConn.setRequestMethod("POST");  
  
     	   
     	   log.debug("请求地址: " + httpUrlConn.getURL());
     	   log.debug("响应内容: " + outputStr);
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式，防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            return buffer.toString();  
        } catch (ConnectException ce) {  
            log.error("Weixin server connection timed out.");  
        } catch (Exception e) {  
            log.error("https request error:{}", e);  
        }  
        return null;  
    }
	
	public static String sendPutRequest(String reqURL, Map<String, String> params, String encodeCharset, String decodeCharset){
  	  	String responseContent = null;
        HttpClient httpClient = new DefaultHttpClient();	    	           
        HttpPut httpPut = new HttpPut(reqURL);
        httpPut.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
		httpPut.setHeader(HTTP.USER_AGENT, USER_AGENT);
        
        List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列
        Set<Entry<String, String>>  paramSet= params.entrySet();
        
        if(null != paramSet && paramSet.size() > 0){
      	  	for(Entry<String,String> entry : paramSet){
      	  		formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	        }
        }	    	         
        try{
      	  	httpPut.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset==null ? Constants.DEFUALT_ENCODING : encodeCharset));
            HttpResponse response = httpClient.execute(httpPut);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
            	String contentType = "";
            	Header[] headers = httpPut.getHeaders(HTTP.CONTENT_TYPE);
            	if(null != headers && headers.length > 0){
            		contentType = headers[0].getValue();
            	}
				 
            	if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
            		responseContent = unGZipContent(entity,decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
            	}else{
            		responseContent = EntityUtils.toString(entity, decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
            	}
            	close(entity); //关闭流
            }
            
            log.debug("请求地址: " + httpPut.getURI());
            log.debug("响应状态: " + response.getStatusLine());
            log.debug("响应内容: " + responseContent);
        }catch(Exception e){
            log.error("与[" + reqURL + "]通信过程中发生异常,堆栈信息如下", e);
        }finally{
            httpClient.getConnectionManager().shutdown();
        }
        return responseContent;

    }
	
	public static String sendPutRequest(String reqURL, String sendData,boolean isGzip, boolean isEncoder, String encodeCharset, String decodeCharset){
		long responseLength = 0;//响应长度
		String responseContent = null; //响应内容
		HttpClient httpClient = new DefaultHttpClient(); 
		   
		HttpPut httpPut = new HttpPut(reqURL);  
		   
		httpPut.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
		httpPut.setHeader(HTTP.USER_AGENT, USER_AGENT);
		   
		try{
           if(isEncoder){
               List<NameValuePair> formParams = new ArrayList<NameValuePair>();
               for(String str : sendData.split("&")){
                   formParams.add(new BasicNameValuePair(str.substring(0,str.indexOf("=")), str.substring(str.indexOf("=")+1)));
               }
               
               String params = URLEncodedUtils.format(formParams, encodeCharset==null ? "UTF-8" : encodeCharset);
               if(isGzip) {
             	  ByteArrayOutputStream baos = gZipContent(params); 
		              
             	  httpPut.setEntity(new ByteArrayEntity(baos.toByteArray()));
               } else {
             	  httpPut.setEntity(new StringEntity(params));
               }
           }else{
         	  if(isGzip) {
             	  ByteArrayOutputStream baos = gZipContent(sendData); 
		              
             	  httpPut.setEntity(new ByteArrayEntity(baos.toByteArray()));
               } else {
             	  httpPut.setEntity(new StringEntity(sendData));
               }
           }
            
           HttpResponse response = httpClient.execute(httpPut);
           HttpEntity entity = response.getEntity();
           if (null != entity) {
         	  String contentType = "";
         	  Header[] headers = httpPut.getHeaders(HTTP.CONTENT_TYPE);
         	  if(null != headers && headers.length > 0){
         		  contentType = headers[0].getValue();
         	  }
				 
         	  if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
         		  responseContent = unGZipContent(entity,decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
         	  }	else {
         		  responseContent = EntityUtils.toString(entity, decodeCharset==null ? Constants.DEFUALT_ENCODING : decodeCharset);
         	  }
         	  close(entity); 
           }
			 
           log.debug("请求地址: " + httpPut.getURI());
           log.debug("响应状态: " + response.getStatusLine());
           log.debug("响应长度: " + responseLength);
           log.debug("响应内容: " + responseContent);
		   
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
		} finally{
			httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
		}  
		return responseContent;
	}
	
	public static String sendDeleteRequest(String reqURL, String encoding){
		long responseLength = 0;//响应长度
		String responseContent = null; //响应内容
		HttpClient httpClient = new DefaultHttpClient(); 
		   
		HttpDeleteOverride httpDelete = new HttpDeleteOverride(reqURL);  
		   
		httpDelete.setHeader(HTTP.CONTENT_TYPE,GZIP_CONTENT_TYPE);
		httpDelete.setHeader(HTTP.USER_AGENT, USER_AGENT);
		   
		try {
		    HttpResponse response = httpClient.execute(httpDelete);
		    HttpEntity entity=response.getEntity();
		    if(entity!=null){
		    	responseLength=entity.getContentLength();
		    	String contentType="";
		    	Header[] headers=httpDelete.getHeaders(HTTP.CONTENT_TYPE);
		    	if(headers!=null && headers.length>0){
		    		contentType=headers[0].getValue();
		    	}
				 
		    	if(contentType.equalsIgnoreCase(GZIP_CONTENT_TYPE)){
		    		responseContent = unGZipContent(entity,encoding==null ? Constants.DEFUALT_ENCODING : encoding);
		    	}else{
		    		responseContent = EntityUtils.toString(entity, encoding==null ? Constants.DEFUALT_ENCODING : encoding);
		    	}
				 
		    	close(entity); 
		    }
			 
		    log.debug("请求地址: " + httpDelete.getURI());
		    log.debug("响应状态: " + response.getStatusLine());
		    log.debug("响应长度: " + responseLength);
		    log.debug("响应内容: " + responseContent);

		   
		} catch (ClientProtocolException e) {
		    e.printStackTrace();
		    log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下", e);
		} catch (IOException e) {
		    e.printStackTrace();
		    log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);

		} finally{
		    httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源
		}  
		return responseContent;
	}
	
	/**
	   * 解压
	   * @param entity
	   * @param encoding
	   * @return
	   * @throws java.io.IOException
	   */
	public static String unGZipContent(HttpEntity entity,String encoding) throws IOException {	
		String responseContent = "";
		GZIPInputStream gis = new GZIPInputStream(entity.getContent());  
		int count = 0;  
		byte data[] = new byte[1024];  
		while ((count = gis.read(data, 0, 1024)) != -1) {  
			String str = new String(data, 0, count,encoding);  
			responseContent += str;
		}
		return responseContent;
	}
	
	/**
	   * 压缩
	   * @param sendData
	   * @return
	   * @throws java.io.IOException
	   */
	public static ByteArrayOutputStream gZipContent(String sendData) throws IOException{
		if (StringUtils.isBlank(sendData)) {   
		     return null;   
		} 
		
		ByteArrayOutputStream originalContent = new ByteArrayOutputStream();  
		originalContent.write(sendData.getBytes("UTF-8"));  
		  
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		GZIPOutputStream gzipOut = new GZIPOutputStream(baos);  
		originalContent.writeTo(gzipOut);  
		gzipOut.close();      
		return baos;
	}
	
	private static void close(HttpEntity entity) throws IOException {
		if (entity == null) {  
            return;  
		}  
		if (entity.isStreaming()) {  
			final InputStream instream = entity.getContent();  
			if (instream != null) {  
				instream.close();  
			}  
		}
	}
	
	
	/**
	 * 上传图片
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @return
	 */
	public static String formUpload(String urlStr, Map<String, String> textMap,
			Map<String, String> fileMap) {
		String res = "";
		HttpURLConnection conn = null;
		String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn
					.setRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Entry entry = (Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append(
							"\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""
							+ inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Entry entry = (Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					File file = new File(inputValue);
					String filename = file.getName();
					String contentType = new MimetypesFileTypeMap()
							.getContentType(file);
					if (filename.endsWith(".png")) {
						contentType = "image/png";
					}
					if (contentType == null || contentType.equals("")) {
						contentType = "application/octet-stream";
					}

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append(
							"\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""
							+ inputName + "\"; filename=\"" + filename
							+ "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

					out.write(strBuf.toString().getBytes());

					DataInputStream in = new DataInputStream(
							new FileInputStream(file));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			log.error("发送POST请求上传文件出错。url:"+urlStr, e);
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}
}
